﻿namespace Pub.Class
{
    using System;
    using System.Collections.Generic;

    public static class TasksTimer
    {
        private static readonly ISafeDictionary<string, Timer> tasksInfo = new SafeDictionarySlim<string, Timer>();

        public static void AddTask(TaskInfo task)
        {
            if (tasksInfo.ContainsKey(task.Class))
            {
                RemoveTask(task.Class);
            }
            Timer timer = new Timer(true);
            Action action = () => SingletonAddIn<IPlugin>.Instance(task.Class + "," + task.Assembly).Main(new string[] { task.Parameter });
            if (task.Interval > 0)
            {
                timer.Start(action, task.Interval, task.Degree);
            }
            if (!task.HHmm.IsNullEmpty() && (task.HHmm.Length == 5))
            {
                timer.Start(action, task.HHmm, task.Degree);
            }
            tasksInfo.Add(task.Class, timer);
        }

        public static void AddTasks(IList<TaskInfo> taskInfoList)
        {
            foreach (TaskInfo info in taskInfoList)
            {
                AddTask(info);
            }
        }

        public static void RemoveAll()
        {
            foreach (KeyValuePair<string, Timer> pair in tasksInfo)
            {
                RemoveTask(pair.Key);
            }
        }

        public static void RemoveTask(string className)
        {
            if (!tasksInfo.ContainsKey(className))
            {
                tasksInfo[className].Stop();
                tasksInfo.Remove(className);
            }
        }
    }
}

